/*
 *@本JS功能：班级管理
 *@本js作者：杨锡君
 *@编写时间：2017年10月31日
 */
$(function() {
    function changedatetime(date) {
        var datetime = new Date(date);

        var year = datetime.getFullYear(); //获取当前年份
        var month = datetime.getMonth() + 1; //获取当前月份
        if(month < 10)
            month = "0" + month;
        var riqi = datetime.getDate(); //获取当前日期
        if(riqi < 10)
            riqi = "0" + riqi;
        var xs = datetime.getHours();
        if(xs < 10)
            xs = "0" + xs;
        var fz = datetime.getMinutes();
        if(fz < 10)
            fz = "0" + fz;
        var miao = datetime.getSeconds();
        if(miao < 10)
            miao = "0" + miao;
        return year + "-" + month + "-" + riqi + " " + xs + ":" + fz ;
    }
    var Alert1 = new Alert();
    var confirm1 = new Confirm();
    var confirm2 = new Confirm();
    var loading1 = new Loading();
    loading1.init();
    var $tableBox = $(".tableBox");
    var th = "<tr>" +
        "<th class=\"col-lg-8\">试卷名称</th>" +
        "<th class=\"col-lg-2\">选择班级</th>" +
        "<th class=\"col-lg-2\">操作</th>" +
        "</tr>";

    function tabelModel(opt,url) {
        var str = "";
        var btn = "";
        var strs = "";
        if(opt.examState == 0){
            str = "未考试";
            strs =  "<a href=\"javascript:;\" data-name='"+  opt.fileName.substring(0,opt.fileName.indexOf(".doc")) +"' data-courseid="+ opt.courseId +" data-id=" + opt.onlinequestionId + "  class=\"testBtn\">开始考试</a>";
            btn = "<a href=\"javascript:;\"  data-courseid="+ opt.courseId +" data-id=" + opt.onlinequestionId + "   class=\"editBtn\">修改</a>" +
                "<a href=\"javascript:;\"  data-courseid="+ opt.courseId +" data-id=" + opt.onlinequestionId + "   class=\"delTest\">删除</a>";
        }
        if(opt.examState == 1){
            str = "已考试";
            strs =  "<a href=\"javascript:;\" data-name='"+  opt.fileName.substring(0,opt.fileName.indexOf(".doc")) +"' data-courseid="+ opt.courseId +" data-id=" + opt.onlinequestionId + "  class=\"testBtn\">开始考试</a>";
        }
        return "<tr data-num=\"0\">" +
            "<td class=\"col-lg-6\" title=" + opt.fileName.substring(0,opt.fileName.indexOf(".doc")) + ">" + opt.fileName.substring(0,opt.fileName.indexOf(".doc")) + "</td>" +
            // "<td class=\"col-lg-2\">" + str + "</td>" +
            "<td class=\"col-lg-2\">" +
            strs+
            "</td>" +
            "<td class=\"col-lg-2\">" +
            "<a href='javascript:;' data-html='"+ opt.textjson +"'  data-url="+ url+ opt.fileName +"  class=\"previewTest hadTest\" data-courseid="+ opt.courseId +" href=\"javscript:;\">查看</div>"+
            btn+
            "</td>" +
            "</tr>";
    }
    var pop = "<div style='display: block;width:840px;left: 50%;margin-left: -420px;' class=\"popup box\">"
        +"<div class=\"popup_box\">"
        +"<div class=\"popup_contenthead\">班级列表<img style='top: 30%;position: absolute;' class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>"
        +"<div class=\"popup_content\"\">"
        +"<table class=\"tableBox\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"></table>"
        +"</div>"
        +"<div style='width: 145px;' class=\"popup_btn\">"
        +"<a class=\"popup_confirm testBegin hover-btn\">开始考试</a>"
        +"</div>"
        +"<div class=\"clear\"></div>"
        +"</div>"
        +"</div>";
    var ths = "<tr>" +
        "<th class=\"col-lg-1\"><input type=\"checkbox\" name=\"controlAll\" id=\"controlAll\" class=\"allCheck\"></th>" +
        "<th class=\"col-lg-4\">班级/申请班</th>" +
        "<th class=\"col-lg-2\">班级状态</th>" +
        "<th class=\"col-lg-2\">试卷状态</th>" +
        "<th class=\"col-lg-3\">考试结束时间</th>" +
        "</tr>";
    function info(str){
        var stm =  "<div style='z-index: 2;display:block;' class=\"popup info\">"
            +"<div class=\"popup_box\">"
            +"<div class=\"popup_contenthead\">提示信息<img style='top: 30%;position: absolute;'  class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>"
            +"<div class=\"popup_content\">班级:"
            +str
            +"</div>"
            +"<div class=\"popup_btn\">"
            +"<a class=\"popup_confirm exportBtn hover-btn\">确定</a>"
            +"<a class=\"popup_close exportCancle hover-btn\">取消</a>"
            +"</div>"
            +"<div class=\"clear\"></div>"
            +"</div>"
            +"</div>";
        return stm;
    }
    function tabelModels(opt) {
        var str = "";
        var string = "";
        var str1 = "";
        if(opt.classExamState == 0){
            str = "未考试";
        }
        if(opt.classExamState == 1){
            str = "已考试";
        }
        if(opt.classExamState == 2){
            str = "考试中";
        }

        if(opt.classExamState == 0 && opt.examState == 0){
            str1 = "未考试";
        }
        if(opt.classExamState == 0 && opt.examState == 1){
            str1 = "未考试";
        }
        if(opt.classExamState == 1 && opt.examState == 0){
            str1 = "未考试";
        }
        if(opt.classExamState == 1 && opt.examState == 1){
            str1 = "考试结束";
        }
        if(opt.classExamState == 2 && opt.examState == 1 && opt.isEnd==1){
            str1 = "考试结束";
        }
        if(opt.classExamState == 2 && opt.examState == 0){
            str1 = "未考试";
        }
        if(opt.classExamState == 2 && opt.examState == 1 && opt.isEnd==0){
            str1 = "已考试";
        }
        // if(opt.examState == 0){
        //     str1 = "未考试";
        // }
        // if(opt.examState == 1){
        //     str1 = "已考试";
        // }

        if(opt.classExamState == 0 && opt.examState == 0  ){
            string = "<input onlinequestionid='"+ opt.onlinequestionId +"' examstate="+ opt.classExamState +" name="+ opt.className +"  data-classid=" + opt.classId + " value=\"0\" name=\"selecteds\" type=\"checkbox\" class=\"oneCheck\" />";
        }
        if(opt.classExamState == 0 && opt.examState == 1  ){
            string = "<input onlinequestionid='"+ opt.onlinequestionId +"' examstate="+ opt.classExamState +" name="+ opt.className +"  data-classid=" + opt.classId + " value=\"0\" name=\"selecteds\" type=\"checkbox\" class=\"oneCheck\" />";
        }
        if(opt.classExamState == 1 && opt.examState == 0  ){
            string = "<input onlinequestionid='"+ opt.onlinequestionId +"' examstate="+ opt.classExamState +" name="+ opt.className +"  data-classid=" + opt.classId + " value=\"0\" name=\"selecteds\" type=\"checkbox\" class=\"oneCheck\" />";
        }
        var endTime =  "";
        if( opt.endTime != null &&  opt.endTime != "" &&   opt.endTime != undefined){
            endTime =  changedatetime(opt.endTime);
        }
        return "<tr data-num=\"0\">" +
            "<td class=\"col-lg-1\">"+ string +"</td>" +
            "<td class=\"col-lg-4\" title=" + opt.className + ">" + opt.className + "</td>" +
            "<td class=\"col-lg-2\">"+ str +"</td>" +
            "<td class=\"col-lg-2\">" + str1 + "</td>" +
            "<td class=\"col-lg-3\" title='"+ endTime +"'>" + endTime + "</td>" +
            "</tr>";
    }
    var classMana = {
        init: function() {
            this.bindEvent();
        },
        bindEvent: function() {
            var self = this;
            $(".iconfont").html(result.paramData.courseTitle);
            $(".courseName").html(result.paramData.courseName);
            var json = {
                "courseId": parseInt(result.paramData.courseId)
            };
            self.tableList(json);
            $(".testGenerate").off("click").on("click", function() {
                self.testGenerateEvent(result.paramData.courseId,result.paramData.courseName,result.paramData.courseTitle);
            });
        },
        tableList: function(jsons) {
            var self = this;
            var json = JSON.stringify(jsons);
            loading1.show();
            $.ajax({
                type: "post",
                url: "getTestPaperByCouId",
                data: {
                    "jsonStr": json
                },
                async: true,
                success: function(msg) {
                    loading1.hide();
                    msg = JSON.parse(msg);
                    $tableBox.empty();
                    if(msg.testPaperList.length != 0) {
                        //列表
                        var tabel = "";
                        var url = msg.url;
                        $.map(msg.testPaperList, function(opt) {
                            tabel += tabelModel(opt,url);
                        });
                        $tableBox.append(th + tabel);
                        self.clickEvent();
                        self.delListEvent();
                    } else {
                        var trImg = "<tr><td colspan='3'><img style='position:relative;margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td></tr>";
                        $tableBox.append(th + trImg)
                    }

                },
                error:function () {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;
                }
            });

        },
        clickEvent:function () {
            // 预览
            var self = this;
            $(".previewTest").off("click").click(function(){
                $(".popup,.mb").show();
                $(".downText").attr("href",$(this).attr("data-url"));
                var text = unescape($(this).attr("data-html"));
                text = text.replace(/\(\+\)/g,"(&emsp;&emsp;)");
                $(".popup_content").html(text);
            });
            $(".popup_img").off("click").click(function(){
                $(".popup,.mb").hide();
            });
            // 修改
            $(".editBtn").off("click").click(function(){
                var json = JSON.stringify({
                    "pageName":"testGenerateEditDetail",
                    "paramData":{
                        "courseId":$(this).attr("data-courseid"),
                        "courseName":result.paramData.courseName,
                        "courseTitle":result.paramData.courseTitle,
                        "onlinequestionId":$(this).attr("data-id")
                    }
                });
                window.location.href ="skipPage?jsonStr="+json
            });
            // 考试跳转
            $(".testBtn").off("click").click(function(){
                // var json = JSON.stringify({
                //     "pageName":"testGenerateClassList",
                //     "paramData":{
                //         "courseId":$(this).attr("data-courseid"),
                //         "courseName":result.paramData.courseName,
                //         "onlinequestionId":$(this).attr("data-id"),
                //         "courseTitle":result.paramData.courseTitle,
                //         "textName":$(this).attr("data-name")
                //     }
                // });
                // window.location.href ="skipPage?jsonStr="+json


                var id = $(this).attr("data-courseid");
                var onlinequestionId = $(this).attr("data-id");
                self.getClassEvent(id,onlinequestionId);

            });
        },
        getClassEvent:function(id,onlinequestionId){
            var self = this;
            $(".mb").show();
            $("body").append(pop);
            var json = JSON.stringify({"courseId":parseInt(id),"onlinequestionId":parseInt(onlinequestionId)});
            $.ajax({
                type: "post",
                url: "getAllClassStateByTeaId",
                async: true,
                data:{
                    "jsonStr":json
                },
                success: function(msg) {
                    loading1.hide();
                    msg = JSON.parse(msg);
                    $(".box .tableBox").empty();
                    if(msg.result == "success"){
                        if(msg.classList.length != 0 && msg.classList != null) {
                            //列表
                            var tabel = "";
                            var url = msg.url;
                            $.map(msg.classList, function(opt) {
                                tabel += tabelModels(opt,url);
                            });
                            $(".box .tableBox").append(ths + tabel);
                            $("#controlAll").off("click").click(function() {

                                var checklist = document.getElementsByClassName("oneCheck");
                                if(document.getElementById("controlAll").checked) {
                                    for(var i = 0; i < checklist.length; i++) {
                                        checklist[i].checked = 1;
                                        checklist[i].value = "1";
                                    }
                                } else {
                                    for(var j = 0; j < checklist.length; j++) {
                                        checklist[j].checked = 0;
                                        checklist[j].value = "0";
                                    }
                                }

                            });
                            $(".oneCheck").off("change").change(function() {

                                if($(this).val() == "0") {
                                    $(this).val("1");
                                } else {
                                    $(this).val("0");
                                }
                            });
                        } else {
                            var trImg = "<tr><td colspan='3'><img style='position:relative;margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td></tr>";
                            $(".box .tableBox").append(ths + trImg)
                        }
                        $(".testBegin").off("click").click(function () {
                            self.delListEvents(id,onlinequestionId);
                        });
                        $(".box .popup_img").off("click").click(function () {
                            $(".mb").hide();
                            $(".box").remove();
                            $(".masking").hide();
                            $(".info").remove();
                        });
                    }else{
                        Alert1.content = msg.msg;
                        Alert1.success = function () {
                          window.location.reload(true);
                        };
                        Alert1.init();
                        Alert1.show();
                    }

                },
                error:function () {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;
                }
            });
        },
        delListEvents: function(id,onlinequestionId) {
            var self = this;
            if($(".oneCheck[value=1]").length == 0) {
                Alert1.content = "请选择要考试的班级";
                Alert1.init();
                Alert1.show();
            } else {

                confirm1.content = "确定对选中的班级开始考试吗？";
                confirm1.success = function () {
                    var list = [];
                    var list1 = [];
                    var list2 = [];
                    for(var i = 0; i < $(".oneCheck[value=1]").length; i++) {
                        list.push({"classId":parseInt($(".oneCheck[value=1]").eq(i).attr("data-classid")),"examMark":2,"onlinequestionId":parseInt($(".oneCheck[value=1]").eq(i).attr("onlinequestionid"))});
                        list1.push($(".oneCheck[value=1]").eq(i).attr("examstate"));
                        list2.push($(".oneCheck[value=1]").eq(i).attr("name"));
                    }
                    for(var i = 0; i < $(".oneCheck[value=0]").length; i++) {
                        list.push({"classId":parseInt($(".oneCheck[value=0]").eq(i).attr("data-classid")),"examMark":0});
                    }
                    var jsons = JSON.stringify({"courseId":parseInt(id),"onlinequestionId":parseInt(onlinequestionId),"list":list});
                    if(list1.indexOf("1") != -1){
                        var list3 = [];
                        $(".masking").show();
                        for(var i= 0;i<list1.length;i++){
                            if(list1[i] == "1"){
                                list3.push(list2[i]);
                            }
                        }
                        $("body").append(info(list3.join()+"已考试,继续考试会覆盖成绩，确定继续吗？"));
                        $(".info .exportBtn").off("click").click(function () {
                            loading1.show();
                            $.ajax({
                                type: "post",
                                url: "startExame",
                                data: {
                                    "jsonStr":jsons
                                },
                                success: function(msg){
                                    loading1.hide();
                                    msg = JSON.parse(msg);
                                    if(msg.resultFlag == true){
                                        // $(".mb").hide();
                                        // $(".box").remove();
                                        $(".masking").hide();
                                        $(".info").remove();
                                        var json = {
                                            "courseId": parseInt(result.paramData.courseId)
                                        };
                                        self.tableList(json);
                                        // window.location.reload(true);
                                        self.getClassEvent(id,onlinequestionId);
                                    }else{
                                        Alert1.content = msg.msg;
                                        Alert1.init();
                                        Alert1.show();
                                    }
                                },
                                error:function () {
                                    loading1.hide();
                                    var json = JSON.stringify({
                                        "pageName": "error"
                                    });
                                    window.location.href = "skipPage?jsonStr=" + json;
                                }
                            });
                        });
                        $(".info .exportCancle").off("click").click(function () {
                            $(".masking").hide();
                            $(".info").remove();

                        });
                        $(".info .popup_img").off("click").click(function () {
                            $(".masking").hide();
                            $(".info").remove();

                        });
                    }else{
                        loading1.show();
                        $.ajax({
                            type: "post",
                            url: "startExame",
                            data: {
                                "jsonStr":jsons
                            },
                            success: function(msg){
                                loading1.hide();
                                msg = JSON.parse(msg);
                                if(msg.resultFlag == true){
                                    // $(".mb").hide();
                                    // $(".box").remove();
                                    // window.location.reload(true);
                                    var json = {
                                        "courseId": parseInt(result.paramData.courseId)
                                    };
                                    self.tableList(json);
                                    self.getClassEvent(id,onlinequestionId);
                                }else{
                                    Alert1.content = msg.msg;
                                    Alert1.init();
                                    Alert1.show();
                                }
                            },
                            error:function () {
                                loading1.hide();
                                var json = JSON.stringify({
                                    "pageName": "error"
                                });
                                window.location.href = "skipPage?jsonStr=" + json;
                            }
                        });
                    }


                };
                confirm1.init();
                confirm1.show();




            }
        },
        testGenerateEvent:function (id,name,title) {
            // 生成试题
            var json = JSON.stringify({
                "pageName":"testGenerateDetail",
                "paramData":{
                    "courseId":id,
                    "courseName":name,
                    "courseTitle":title
                }
            });
            window.location.href ="skipPage?jsonStr="+json
        },
        delListEvent: function() {
            var self = this;
            $(".delTest").off("click").click(function(){
                var arr = [];
                arr.push(Number($(this).attr("data-id")));
                confirm1.content = "确认删除试卷吗";
                confirm1.success = function () {
                    loading1.show();
                    $.ajax({
                        type:"post",
                        url:"delOnlineQuestion",
                        async:true,
                        data:{
                            "jsonStr":JSON.stringify(arr)
                        },
                        success:function(msg){
                            loading1.hide();
                            msg = JSON.parse(msg);
                            if(msg.result == "success"){
                                Alert1.content = "删除试卷成功";
                                Alert1.success = function(){
                                    var json = {
                                        "courseId": parseInt(result.paramData.courseId)
                                    };
                                    self.tableList(json);
                                };
                                Alert1.init();
                                Alert1.show();
                                return false;

                            }else{
                                Alert1.content = msg.msg;
                                Alert1.init();
                                Alert1.show();
                                return false;
                            }
                        }
                    });
                };
                confirm1.init();
                confirm1.show();

            });
        }
    };
    classMana.init();
});